//
//  String+Extension.swift
//  AoNongOA
//
//  Created by zwb on 16/9/5.
//  Copyright © 2025 aowang. All rights reserved.
//

import Foundation
struct AssociatedKeys {
    static var testNameKey: String = "testNameKey"
}

extension String {
    
    // unicode解码
    func unicode2Str() -> String {
        let wI = NSMutableString( string: self )
        CFStringTransform( wI, nil, "Any-Hex/Java" as NSString, true )
        return wI as String
    }
    /// 替换手机号中间四位
    ///
    /// - Returns: 替换后的值
    func replacePhone() -> String {
        guard self.count > 6 else {
            return self
        }
        let start = self.index(self.startIndex, offsetBy: 3)
        let end = self.index(self.startIndex, offsetBy: 7)
        let range = Range(uncheckedBounds: (lower: start, upper: end))
        return self.replacingCharacters(in: range, with: "****")
    }
    
    
    
    /// 从左往右截取 字符x 之前  不包含 x   只处理首次遇到     后面的为剩余
    func preCharSeq(char:String) -> (String,String) {
        var tempS = ""
        var surplus = ""
        var cutDone = false
        for i in self {
            let s = String(i)
            if s == char && cutDone == false {
                cutDone = true
               }  else {
                  if cutDone {
                      surplus += s
                  } else {
                      tempS += s
                  }
                
            }
        }
         return (tempS,surplus)
    }
    // 带括号的表达式  转换   a&&(b||c)&&(e||f)&&d  把 b||c 截取出来 放占位符   placeholder1  placeholder2  等
    // 输入  a&&(b||c)&&(e||f)&&d    输出  a&&placeholder1&&placeholder2&&d  ，【placeholder1 ： b|| c, placeholder2: e||f】
    func dealParenthesis(str:String) -> (String,[String:String]) {
       var tempStr = str.removeAllSapce.removeLineFeed
         
        var result = "" // 累计字符
        var tempInnerStr = ""
        var innerFlag = false // 在括号内的标识
        var innerCount = 0
         var placDic:[String:String] = [:]
        
        tempStr.forEach { c in
            let s = String(c)
              if s == "(" {
                 innerFlag = true
                 innerCount += 1
             } else if s == ")" {
                innerFlag = false
                 let param = "placeholder\(innerCount)"
                result += param
                 placDic.updateValue(tempInnerStr, forKey: param)
                 tempInnerStr = ""
             } else {
                 if innerFlag {
                    tempInnerStr += s
                 } else {
                     result += s
                 }
             }
         }
   
        return (result,placDic)
      }
    
    
    
    
    /// 从左往右截取 字符x 之前  不包含 x   （字符必须是唯一的）
    func preChar(char:String) -> String? {
        if self.contains(char) {
            let range: Range = self.range(of: char)!
            let location: Int = self.distance(from: self.startIndex, to: range.lowerBound)
            let preStr = self.prefix(location)
            return String(preStr)
        } else {
            return nil
        }
    }
    /// 从左往右截取 字符x 之前  包含 x  （字符必须是唯一的）
    func preCharContain(char:String) -> String? {
        if self.contains(char) {
            let range: Range = self.range(of: char)!
            let location: Int = self.distance(from: self.startIndex, to: range.upperBound)
            let preStr = self.prefix(location)
            return String(preStr)
        } else {
            return  nil
        }
    }
    /// 从右往左截取 字符  不包含 x   只处理首次遇到
    func sufCharSeq(char:String) -> (String,String) {
        var tempS = ""
        var surplus = ""
        var cutDone = false
        for i in self.reversed() {
            let s = String(i)
            if s == char  && cutDone == false {
                cutDone = true
              }  else {
                  if cutDone {
                      surplus = "\(s)\(surplus)"
                  } else {
                      tempS = "\(s)\(tempS)"
                  }
             }
        }
          return (tempS,surplus)
         
    }
    /// 从右往左截取 字符  不包含 x   （字符必须是唯一的）
    func sufChar(char:String) -> String? {
        if self.contains(char) {
            let range: Range = self.range(of: char)!
            let location: Int = self.distance(from: self.startIndex, to: range.upperBound)
            let preStr = self.suffix(self.count - location)
            return String(preStr)
        } else {
            return nil
        }
    }
    /// 从右往左截取 字符  包含 x    （字符必须是唯一的）
    func sufCharContain(char:String) -> String? {
        if self.contains(char) {
            let range: Range = self.range(of: char)!
            let location: Int = self.distance(from: self.startIndex, to: range.lowerBound)
            let preStr = self.suffix(self.count - location)
            return String(preStr)
        } else {
            return nil
        }
    }
    
    /// 处理万以上的数
    func dealPreW () -> Double? {
        var number = 0.0
        var remainStr = self
        if let preQ = remainStr.preChar(char: "仟") {
            number += preQ.ksLowercase(unit: "仟").doubleWrap
            if let rem = remainStr.sufChar(char: "仟") {
                remainStr = rem
            } else {
                return number
            }
        }
        if let preB = remainStr.preChar(char: "佰") {
            number += preB.ksLowercase(unit: "佰").doubleWrap
            if let rem = remainStr.sufChar(char: "佰") {
                remainStr = rem
            } else {
                return number
            }
        }
        if let preS = remainStr.preChar(char: "拾") {
            number += preS.ksLowercase(unit: "拾").doubleWrap
            if let rem = remainStr.sufChar(char: "拾") {
                remainStr = rem
            } else {
                return number
            }
            
        }
        if let preW = remainStr.preChar(char: "万") {
            number += preW.ksLowercase(unit: "万").doubleWrap
            number  = number * 10000
            return number
        }
        
        return nil
        
    }
    /// 处理万以下的数
    func dealSubW () -> Double? {
        var number = 0.0
        var remainStr = self
        
        if let preQ = remainStr.preChar(char: "仟") {
            number += preQ.ksLowercase(unit: "仟").doubleWrap
            if let rem = remainStr.sufChar(char: "仟") {
                remainStr = rem
            } else {
                return number
            }
        }
        if let preB = remainStr.preChar(char: "佰") {
            number += preB.ksLowercase(unit: "佰").doubleWrap
            
            if let rem = remainStr.sufChar(char: "佰") {
                remainStr = rem
            } else {
                return number
            }
            
        }
        if let preS = remainStr.preChar(char: "拾") {
            number += preS.ksLowercase(unit: "拾").doubleWrap
            if let rem = remainStr.sufChar(char: "拾") {
                remainStr = rem
            } else {
                return number
            }
        }
        if let preW = remainStr.preChar(char: "元") {
            number += preW.ksLowercase(unit: "元").doubleWrap
            if let rem = remainStr.sufChar(char: "元") {
                remainStr = rem
            } else {
                return number
            }
        }
        if let preW = remainStr.preChar(char: "整") {
            return number
        }
        if let preW = remainStr.preChar(char: "角") {
            number += preW.ksLowercase(unit: "角").doubleWrap
            if let rem = remainStr.sufChar(char: "角") {
                remainStr = rem
            } else {
                return number
            }
        }
        if let preW = remainStr.preChar(char: "分") {
            number += preW.ksLowercase(unit: "分").doubleWrap
            return number
        }
        return number
    }
    
    
    //    贰仟贰佰贰拾陆万   捌仟贰佰贰拾捌元玖角玖分  大写转小写
    func cpatialMoney2lowercase() -> Double? {
        var number = 0.0
        var remainStr = self
        
        if let preW = remainStr.preCharContain(char: "万") {
            number += preW.dealPreW().doubleWrap
            number += remainStr.sufChar(char: "万")!.dealSubW().doubleWrap
            return number
        } else {
            number += remainStr.dealSubW().doubleWrap
            return number
        }
        
        
    }
    
    
    // 2g位数，传进来，返回该两位数代表的数字
    func ksLowercase(unit:String) -> Double? {
        let number = self.replacingOccurrences(of: "壹", with: "1")
            .replacingOccurrences(of: "贰", with: "2")
            .replacingOccurrences(of: "叁", with: "3")
            .replacingOccurrences(of: "肆", with: "4")
            .replacingOccurrences(of: "伍", with: "5")
            .replacingOccurrences(of: "陆", with: "6")
            .replacingOccurrences(of: "柒", with: "7")
            .replacingOccurrences(of: "捌", with: "8")
            .replacingOccurrences(of: "玖", with: "9")
        
        let intNumber = Double(number) ?? 0
        if unit.contains("仟") {
            return intNumber * 1000.0
        }
        if unit.contains("佰") {
            return intNumber * 100.0
        }
        if unit.contains("拾") {
            return intNumber * 10.0
        }
        if unit.contains("万") {
            return intNumber
        }
        if unit.contains("元") {
            return intNumber
        }
        if unit.contains("角") {
            return intNumber * 0.1
        }
        if unit.contains("分") {
            return intNumber * 0.01
        }
        return nil
        
    }
    
    
    
    /// 人名币大写
    func numberRMM() -> String {
        guard let num = Double(self) else {
            return ""
        }
        let format = NumberFormatter()
        format.locale = Locale(identifier: "zh_CN")
        format.numberStyle = .spellOut
        format.minimumIntegerDigits = 1
        format.minimumFractionDigits = 0
        format.maximumFractionDigits = 2
        let text = format.string(from: NSNumber(value: num)).unwrap
        let sept = self.components(separatedBy: ".")
        let decimals: Double? = sept.count == 2 ? Double("0." + sept.last!) : nil
        return self.formatRMM(text: text, isInt: decimals == nil || decimals! < 0.01)
    }
    
    private func formatRMM(text: String, isInt: Bool) -> String {
        let formattedString = text.replacingOccurrences(of: "一", with: "壹")
            .replacingOccurrences(of: "二", with: "贰")
            .replacingOccurrences(of: "三", with: "叁")
            .replacingOccurrences(of: "四", with: "肆")
            .replacingOccurrences(of: "五", with: "伍")
            .replacingOccurrences(of: "六", with: "陆")
            .replacingOccurrences(of: "七", with: "柒")
            .replacingOccurrences(of: "八", with: "捌")
            .replacingOccurrences(of: "九", with: "玖")
            .replacingOccurrences(of: "十", with: "拾")
            .replacingOccurrences(of: "百", with: "佰")
            .replacingOccurrences(of: "千", with: "仟")
            .replacingOccurrences(of: "〇", with: "零")
        let sept = formattedString.components(separatedBy: "点")
        var intStr = sept[0]
        if sept.count > 0 && isInt {
            // 整数处理
            return intStr.appending("元整")
        } else {
            // 小数处理
            let decStr = sept[1]
            intStr = intStr.appending("元").appending("\(decStr.first!)角")
            if decStr.count > 1 {
                intStr = intStr.appending("\(decStr[decStr.index(decStr.startIndex, offsetBy: 1)])分")
            } else {
                intStr = intStr.appending("零分")
            }
            return intStr
        }
    }
    
    
    
    // 是否纯数字
    var isPureInt: Bool {
        let scan: Scanner = Scanner(string: self)
        var val:Int = 0
        return scan.scanInt(&val) && scan.isAtEnd
    }
 
    // 把  abcd  直接分割成  [a,b,c,d] 数组
    public var charactersArray: [Character] {
        return Array(self)
    }
    
    /*
     *去掉所有空格
     */
    var removeAllSapce: String {
        return self.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    }
    /*
     *去掉换行
     */
    var removeLineFeed: String {
        return self.replacingOccurrences(of: "\n", with: "")
    }
    
    
    func isEmpty() -> Bool {
        return self.count == 0
    }
    // 校验传入的正则
    func valiRagular(_ str:String) -> Bool {
        return self.validateWithRegex(regex: str)
    }
    // 校验正整数
     func validateInteger() -> Bool {
         let regex = "^[1-9]\\d*|0$"
        return self.validateWithRegex(regex: regex)
    }
    
    /// 保留两位小数
    func validateTwoDecimal() -> Bool {
        //        let regex = "^[0-9]+(.[0-9]{2})?$"
        let regex = "^(-)?[0-9]*((\\.)[0-9]{0,2})?$"
        
//        let regex = "^\\d+(\\.\\d{1,2})?$"
        
        return self.validateWithRegex(regex: regex)
         
    }
    /// 保留三位小数
    func validateThreeDecimal() -> Bool {
        //        let regex = "^[0-9]+(.[0-9]{2})?$"
        let regex = "^(-)?[0-9]*((\\.)[0-9]{0,3})?$"
        return self.validateWithRegex(regex: regex)
    }
    /// 保留4位小数
    func validateFourDecimal() -> Bool {
        //        let regex = "^[0-9]+(.[0-9]{2})?$"
        let regex = "^(-)?[0-9]*((\\.)[0-9]{0,4})?$"
        return self.validateWithRegex(regex: regex)
    }
    /// 非负整数 和 空
    func validateNonNegativeInteger() -> Bool {
        let regex = "^\\d*$"
        return self.validateWithRegex(regex: regex)
    }
    
    /// 校验身份证
    func validateIDCard() -> Bool {
        let regex15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$"
        let regex18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$"
        return self.validateWithRegex(regex: regex15) || self.validateWithRegex(regex: regex18)
    }
    
    /// 校验手机号
    func validatePhonenumber() -> Bool {
        let regex = "^(1)\\d{10}$"
        return self.validateWithRegex(regex: regex)
    }
    
    /// 密码的强度必须是包含大小写字母和数字的组合，不能使用特殊字符，长度在6-18之间
    func validatePassword6() -> Bool {
        let regex = "^(?=.*\\d)(?=.*[a-zA-Z]).{6,18}$"
        return self.validateWithRegex(regex: regex)
    }
    /// 密码的强度必须是包含大小写字母和数字的组合，不能使用特殊字符，长度在8-18之间
    func validatePassword8() -> Bool {
        let regex = "^(?=.*\\d)(?=.*[a-zA-Z]).{8,18}$"
        return self.validateWithRegex(regex: regex)
    }
    // 正则表达式校验
    func validateWithRegex(regex: String) -> Bool {
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        return predicate.evaluate(with: self)
    }
    
    //至少8个字符,至少1个字母和1个数字
    func validate8word_C_1Letter_1Num() -> Bool {
        let regex = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"
        return self.validateWithRegex(regex: regex)
    }
    //至少8个字符，至少1个字母，1个数字和1个特殊字符
    func validate8word_C_1Letter_1Num_1Other() -> Bool {
        let regex = "^(?=.*[A-Za-z])(?=.*\\\\d)(?=.*[$@$!%*#?&])[A-Za-z\\\\d$@$!%*#?&]{8,}$"
        return self.validateWithRegex(regex: regex)
    }
    
    
    //至少1个大写字母，(?=.*?[A-Z]) 最小8个长度
    func R_Letter() -> Bool {
        let regex = "^(?=.*[A-Za-z]).{8,}$"
        return self.validateWithRegex(regex: regex)
    }
    //至少1位数字，(?=.*?[0-9])  最小8个长度
    func R_number() -> Bool {
        let regex = "^(?=.*?[0-9]).{8,}$"
        return self.validateWithRegex(regex: regex)
    }
    //至少有1个特殊字符，(?=.*?[#?!@$%^&*-]) 最小8个长度
    func R_special() -> Bool {
        let regex = "^(?=.*?[#?!@$%^&*-]).{8,}$"
        return self.validateWithRegex(regex: regex)
    }
    
    
   static func isStringANumber(_ string: String) -> Bool {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        return numberFormatter.number(from: string) != nil
    }
    
    var ks_selected: Bool {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.testNameKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        
        get {
            return (objc_getAssociatedObject(self, &AssociatedKeys.testNameKey) as? Bool) ?? false
        }
    }
    
    
    
    // 特殊字符过滤
    func check() -> String {
        
        let  result = NSMutableString()
        
        // 使用正则表达式一定要加try语句
        
        do {
            
            // - 1、创建规则
            
            let pattern = "[a-z0-9_-]"
            
            // - 2、创建正则表达式对象
            
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            
            // - 3、开始匹配
            
            let res = regex.matches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count))
            
            // 输出结果
            
            for checkingRes in res {
                
                let nn = (self as NSString).substring(with: checkingRes.range) as NSString
                
                result.append(nn as String)
                
            }
            
        }
        catch {
            print(error)
        }
        
        return result as String
        
    }
    
    /*
     *去掉首尾空格 包括后面的换行 \n
     */
    var removeHeadAndTailSpacePro:String {
        let whitespace = NSCharacterSet.whitespacesAndNewlines
        return self.trimmingCharacters(in: whitespace)
    }
    
    func toUIImage() -> UIImage? {
        // 移除可能存在的空格和换行符
           let cleanedBase64String = self.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "")
             
        // 将 Base64 字符串解码为 Data
        guard let imageData = Data(base64Encoded: cleanedBase64String) else {
            return nil
        }
          
        // 使用解码后的 Data 初始化 UIImage
        return UIImage(data: imageData)
    }
      
    
    
    // 驼峰字符串
    var camelName:String {
        var result = ""
        var flag = false
        self.forEach { c in
            let s = String(c)
            if s == "_" {
                flag = true
            } else {
                if flag {
                    result += s.uppercased()
                    flag = false
                } else {
                    result += s
                }
            }
        }
        return result
    }
    // 下划线字符串
    var underscore_name:String {
        var result = ""
        self.forEach { c in
            let num = c.unicodeScalars.map { $0.value }.last!
            let s = String(c)
            if num > 64 && num < 91 {
                result += "_"
                result += s.lowercased()
            } else {
                result += s
            }
        }
        return result
    }
    
    
}

extension String {
    
    
    var filterQuote: String {
        return self.replacingOccurrences(of: "'", with: "\"")
    }
    // swiftlint:disable next identifier_name
    /// SwifterSwift: Safely subscript string with index.
    
    
    /// - Parameter i: index.
    public subscript(safe i: Int) -> Character? {
        guard i >= 0 && i < count else { return nil }
        return self[index(startIndex, offsetBy: i)]
    }
    
    /// SwifterSwift: Safely subscript string within a half-open range.
    ///
    ///        "Hello World!"[6..<11] -> "World"
    ///        "Hello World!"[21..<110] -> nil
    ///
    /// - Parameter range: Half-open range.
    public subscript(safe range: CountableRange<Int>) -> String? {
        guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil }
        guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else { return nil }
        return String(self[lowerIndex..<upperIndex])
    }
    
    /// SwifterSwift: Safely subscript string within a closed range.
    ///
    ///        "Hello World!"[6...11] -> "World!"
    ///        "Hello World!"[21...110] -> nil
    ///
    /// - Parameter range: Closed range.
    public subscript(safe range: ClosedRange<Int>) -> String? {
        guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil }
        guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else { return nil }
        return String(self[lowerIndex..<upperIndex])
    }
     
}



extension NSString {
    func sizeWithFont(font: UIFont, maxSize: CGSize) -> CGSize {
        return self.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil).size
    }
}

extension String {
    
    // 某些数值显示时，如果是空，用0代替
    var zero4empty:String {
        if self.isEmpty {
            return "0"
        } else {
            return self
        }
    }
    
    var length: Int {
        get {
            return self.count
        }
    }
    
    var OCString: NSString {
        get {
            return self as NSString
        }
    }
    
    
    var lastPathComponent: String {
        get {
            return self.OCString.lastPathComponent
        }
    }
    
    func isAllDigit() -> Bool {
        for uni in unicodeScalars {
            if CharacterSet.decimalDigits.contains(UnicodeScalar(uni.value)!) {
                continue
            }
            return false
        }
        return true
    }
    // 字符宽度
    func sizeWithFont(font: UIFont, maxSize: CGSize) -> CGSize {
        return self.OCString.sizeWithFont(font: font, maxSize: maxSize)
    }
    
    
    
}
// MARK: 字符串转字典
extension String {
    
    // 文本的实际高度
    func heightWithStringAttributes(attributes : [NSAttributedString.Key : Any], fixedWidth : CGFloat) -> CGFloat {
        
        guard self.count > 0 && fixedWidth > 0 else {
            return 0
        }
        let size = CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude)
        let text = self as NSString
        let rect = text.boundingRect(with: size, options:.usesLineFragmentOrigin, attributes: attributes, context:nil)
        return rect.size.height
    }
    ///根据宽度跟字体，计算文字的高度
    
    func textAutoHeight(width:CGFloat, font:UIFont) ->CGFloat {
        let string = self as NSString
        
        let origin = NSStringDrawingOptions.usesLineFragmentOrigin
        
        let lead = NSStringDrawingOptions.usesFontLeading
        
        let ssss = NSStringDrawingOptions.usesDeviceMetrics
        
        let rect = string.boundingRect(with:CGSize(width: width, height:0), options: [origin,lead,ssss], attributes: [NSAttributedString.Key.font:font], context:nil)
        
        return rect.height
    }
    
}


extension String {
    
    /// 根据字符分割成数组
    /// - Parameter str: 分割字符
    /// - Returns: 分割后的数组
    func componentsSeparated(by str : Character) -> Array<String> {
        return self.split{$0 == str}.map(String.init)
    }
    
    /// 遍历字符串的每个字符
    /// - Parameter callback: 遍历回调 (索引, 字符)
    func forInChar(_ callback : (Int, Character) -> Void) {
        for i in 0..<self.count {
            let char : Character = self[self.index(self.startIndex, offsetBy: i)]
            callback(i, char)
        }
    }
    
    func removewhitespaceAndNewline() -> String {
        let noWhitespaceStr = self.replacingOccurrences(of: " ", with: "")
        let resultStr = noWhitespaceStr.replacingOccurrences(of: "\n", with: "")
        return resultStr
    }
    
    func subTo(_ toIndex: Int) -> String {
        let index : String.Index = self.index(startIndex, offsetBy: toIndex);
        return String(self[..<index]);
    }
    
    func subFrom(_ fromIndex: Int) -> String {
        let index : String.Index = self.index(startIndex, offsetBy: fromIndex);
        return String(self[index..<endIndex]);
    }
    
    func subFrom(fromIndex from: Int, toIndex to: Int) -> String {
        if from > to {
            return self
        }
        
        let index1 = self.index(startIndex, offsetBy: from);
        let index2 = self.index(startIndex, offsetBy: to);
        return String(self[index1..<index2]);
    }
    
    func rangeOf(str: String) -> NSRange {
        
        if str.count == 0 {
            return NSRange.init(location: 0, length: 0)
        }
        
        let orginStr = self as NSString
        
        return orginStr.range(of: str)
    }
    
    static func format(number count: Int?, zeroText zero: String?) -> String {
        if count == nil {
            return zero != nil ? zero! : ""
        }
        
        if count! >= 10000 {
            let value = Float(count!)/10000.0
            return String(format: "%.2fw+", value)
        }
        
        if count! >= 1000 {
            let value = Float(count!)/1000.0
            return String(format: "%.2fk+", value)
        }
        
        if count! == 0 {
            return zero != nil ? zero! : ""
        }
        
        return "\(count!)"
    }
    
    static func formatNoPlus(number count: Int?, zeroText zero: String?) -> String {
        if count == nil {
            return zero != nil ? zero! : ""
        }
        
        if count! >= 10000 {
            let value = Float(count!)/10000.0
            return String(format: "%.2fw", value)
        }
        
        if count! >= 1000 {
            let value = Float(count!)/1000.0
            return String(format: "%.2fk", value)
        }
        
        if count! == 0 {
            return zero != nil ? zero! : ""
        }
        
        return "\(count!)"
    }
    
    func replace(old: String, str: String) -> String {
        let mutilStr = NSMutableString(string: self)
        mutilStr.replaceOccurrences(of: old, with: str, options: NSString.CompareOptions(rawValue: 1) , range: .init(location: 0, length: mutilStr.length))
        return mutilStr as String
    }
}

extension String {
    // 是否是整数
    var isInteger: Bool {
        guard !self.isEmpty else { return false }
        return self.allSatisfy { $0.isNumber }
    }
    
    // 是否是正整数
    var isPositiveInteger: Bool {
        guard !self.isEmpty else { return false }
        // 不允许负号，且必须全是数字
        return !self.hasPrefix("-") && self.allSatisfy { $0.isNumber }
    }
}
 // 判断一个字符串至少包含一个中文字符
func containsChineseCharacter(_ string: String) -> Bool {
    return string.unicodeScalars.contains { scalar in
        // 检查是否为中文字符（包括常用汉字及扩展范围）
        let isChinese =
            (0x4E00...0x9FFF).contains(scalar.value) ||    // CJK 统一表意文字
            (0x3400...0x4DBF).contains(scalar.value) ||    // CJK 统一表意文字扩展 A
            (0x20000...0x2A6DF).contains(scalar.value) ||  // CJK 统一表意文字扩展 B
            (0x2A700...0x2B73F).contains(scalar.value) ||  // CJK 统一表意文字扩展 C
            (0x2B740...0x2B81F).contains(scalar.value) ||  // CJK 统一表意文字扩展 D
            (0x2B820...0x2CEAF).contains(scalar.value)     // CJK 统一表意文字扩展 E
        
        return isChinese
    }
}
 
